package cool.goodbai.controller;

import cn.dev33.satoken.stp.StpUtil;
import cool.goodbai.api.BaseController;
import cool.goodbai.constant.ApiConstant;
import cool.goodbai.entity.Employ;
import cool.goodbai.entity.Post;
import cool.goodbai.entity.User;
import cool.goodbai.example.EmployExample;
import cool.goodbai.mapper.EmployMapper;
import cool.goodbai.mapper.UserMapper;
import cool.goodbai.service.impl.EmployServiceImpl;
import cool.goodbai.service.impl.PostServiceImpl;
import cool.goodbai.service.impl.UserServiceImpl;
import cool.goodbai.util.PageUtil;
import cool.goodbai.util.StringUtil;
import cool.goodbai.vo.EmployHXYDto;
import cool.goodbai.vo.PageResult;
import cool.goodbai.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(tags = "Employ")
@CrossOrigin
@RestController()
@RequestMapping(ApiConstant.BASE_API_URL + "/employ/")
public class EmployController extends BaseController {
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private PostServiceImpl postService;

    @Autowired
    private EmployServiceImpl employService;

    @Autowired
    private EmployMapper employMapper;

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "默认Get请求", notes = "请求不存在的路径时调用此默认接口")
    @ApiImplicitParam(name = "name", value = "默认字段", required = true, dataTypeClass = String.class)
    @GetMapping(value = "/{name}")
    @ResponseBody
    public String helloWorld(@PathVariable(name = "name") String name) {
        return "Hello " + name;
    }

    @ApiOperation(value = "添加投递状态", notes = "添加投递状态")
    @PostMapping(value = "/insert")
    @ResponseBody
    public Response<Employ> insert(@NotNull @RequestBody Employ employ) {
        try {
            Employ result = employService.insert(employ);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "添加投递状态失败");
        } catch (IOException e) {
            return getFailResult(404, "您已存在投递记录");
        }
    }

    @ApiOperation(value = "删除投递状态", notes = "删除投递状态")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Response<Employ> delete(@RequestParam Long id) {
        try {
            Employ result = employService.delete(id);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "删除投递状态失败");
        }
    }

    @ApiOperation(value = "更新投递状态", notes = "更新投递状态")
    @PostMapping(value = "/update")
    @ResponseBody
    public Response<Employ> update(@RequestBody Employ employ) {
        try {
            Employ temp = employMapper.selectByPrimaryKey(employ.getId());
            if (!Objects.isNull(employ.getStatus())) {
                if (Objects.isNull(temp.getFirstTime())) {
                    employ.setFirstPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setFirstTime(LocalDateTime.now());
                } else if (Objects.isNull(temp.getSecondTime())) {
                    employ.setSecondPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setSecondTime(employ.getSecondTime());
                } else if (Objects.isNull(temp.getThirdTime())) {
                    employ.setThirdPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setThirdTime(LocalDateTime.now());
                } else if (Objects.isNull(temp.getForthTime())) {
                    employ.setForthPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setForthTime(LocalDateTime.now());
                }
            }
            Employ result = employService.update(employ);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "更新投递状态失败");
        }
    }

    @ApiOperation(value = "批量更新投递状态", notes = "批量更新投递状态")
    @PostMapping(value = "/updateStatusByIds")
    @ResponseBody
    public Response<String> updateStatusByIds(@RequestParam String[] employIds, @RequestParam int status) {
        try {
            Arrays.stream(employIds).forEach(id -> {
                Employ employ = employMapper.selectByPrimaryKey(Long.parseLong(id));
                if (Objects.isNull(employ.getFirstTime())) {
                    employ.setFirstPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setFirstTime(LocalDateTime.now());
                } else if (Objects.isNull(employ.getSecondTime())) {
                    return;
                } else if (Objects.isNull(employ.getThirdTime())) {
                    employ.setThirdPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setThirdTime(LocalDateTime.now());
                } else if (Objects.isNull(employ.getForthTime())) {
                    employ.setForthPeople(String.valueOf(StpUtil.getLoginId()));
                    employ.setFirstTime(LocalDateTime.now());
                }
                employ.setStatus(status);
                employService.update(employ);
            });
            return getSuccessResult("Success");
        } catch (RuntimeException e) {
            return getFailResult(404, "批量更新投递状态失败");
        }
    }

    @ApiOperation(value = "根据用户id查询投递记录", notes = "根据用户id查询投递记录")
    @PostMapping(value = "/selectByUserId")
    @ResponseBody
    public Response<Employ> selectByUserId(@RequestParam Long userId) {
        try {
            return getSuccessResult(employService.selectByUserId(userId));
        } catch (RuntimeException e) {
            return getFailResult(404, "根据用户id查询投递记录失败");
        }
    }

    @ApiOperation(value = "查询所有被淘汰的人", notes = "查询所有被淘汰的人")
    @GetMapping(value = "/selectOutMan")
    @ResponseBody
    public PageResult<List<EmployHXYDto>> selectOutMan(@RequestParam Integer current, @RequestParam Integer pageSize) {
        try {
            EmployExample employExample = new EmployExample();
            EmployExample.Criteria criteria = employExample.createCriteria().andStatusEqualTo(3);
            EmployExample.Criteria criteria2 = employExample.createCriteria().andStatusEqualTo(6);
            EmployExample.Criteria criteria3 = employExample.createCriteria().andStatusEqualTo(8);
            employExample.or(criteria2);
            employExample.or(criteria3);
            List<Employ> employs = employMapper.selectByExample(employExample);
            List<EmployHXYDto> res = new ArrayList<>();
            employs.forEach(employ -> {
                EmployHXYDto dto = new EmployHXYDto();

                User user = new User();
                user.setId(employ.getUserId());
                dto.setUserId(userService.select(user, 1, 1).getData().get(0));

                Post post = new Post();
                post.setId(employ.getPostId());
                dto.setPostId(postService.select(post, 1, 1).getData().get(0));

                if (StringUtil.isNotEmpty(employ.getFirstPeople())) {
                    user.setId(Long.valueOf(employ.getFirstPeople()));
                    dto.setFirstPeople(userService.select(user, 1, 1).getData().get(0));
                    dto.setFirstTime(dto.getFirstTime());
                }
                if (StringUtil.isNotEmpty(employ.getSecondPeople())) {
                    user.setId(Long.valueOf(employ.getSecondPeople()));
                    dto.setSecondPeople(userService.select(user, 1, 1).getData().get(0));
                    dto.setSecondTime(employ.getSecondTime());
                }
                if (StringUtil.isNotEmpty(employ.getThirdPeople())) {
                    user.setId(Long.valueOf(employ.getThirdPeople()));
                    dto.setThirdPeople(userService.select(user, 1, 1).getData().get(0));
                    dto.setThirdTime(employ.getThirdTime());
                    dto.setThirdEvaluate(employ.getThirdEvaluate());
                }
                if (StringUtil.isNotEmpty(employ.getForthPeople())) {
                    user.setId(Long.valueOf(employ.getForthPeople()));
                    dto.setForthPeople(userService.select(user, 1, 1).getData().get(0));
                    dto.setForthTime(employ.getForthTime());
                }

                if (!Objects.isNull(employ.getTime())) {
                    dto.setTime(employ.getTime());
                }
                if (!Objects.isNull(employ.getStatus())) {
                    dto.setStatus(employ.getStatus());
                }
                if (!Objects.isNull(employ.getId())) {
                    dto.setId(employ.getId());
                }
                if (!Objects.isNull(employ.getUtcCreate())) {
                    dto.setUtcCreate(employ.getUtcCreate());
                }
                if (!Objects.isNull(employ.getUtcModify())) {
                    dto.setUtcModify(employ.getUtcModify());
                }
                if (StringUtil.isNotEmpty(employ.getCreateBy())) {
                    dto.setCreateBy(employ.getCreateBy());
                }
                if (StringUtil.isNotEmpty(employ.getModifyBy())) {
                    dto.setModifyBy(employ.getModifyBy());
                }
                if (!Objects.isNull(employ.getValid())) {
                    dto.setValid(employ.getValid());
                }
                if (StringUtil.isNotEmpty(employ.getRemark())) {
                    dto.setRemark(employ.getRemark());
                }
                res.add(dto);
            });
            int end = Math.min(res.size() - (current - 1) * pageSize, pageSize);
            return new PageResult<>(res.subList((current - 1) * pageSize, (current - 1) * pageSize + end), current, pageSize, true, (long) res.size(), 0);
        } catch (RuntimeException e) {
            return getFailPageResult(404, "根据用户id查询投递记录失败");
        }
    }

    @ApiOperation(value = "查询投递状态", notes = "查询投递状态")
    @PostMapping(value = "/select")
    @ResponseBody
    public PageResult<List<EmployHXYDto>> select(@RequestParam Integer current, @RequestParam Integer pageSize, @RequestParam(required = false) Long id,
                                                 @RequestParam(required = false) String userId, @RequestParam(required = false) String postId,
                                                 @RequestParam(required = false) String college,
                                                 @RequestParam(required = false) Integer[] status, @RequestParam(required = false) String firstPeople,
                                                 @RequestParam(required = false) String secondPeople, @RequestParam(required = false) String thirdPeople) {
        try {
            // 校验分页参数
            PageUtil.checkPageParam(current, pageSize);
            Employ employ = new Employ();
            List<EmployHXYDto> result = new ArrayList<>();
            List<EmployHXYDto> res = new ArrayList<>();
            // 第一种情况 岗位和用户都传值了
            if (StringUtil.isNotEmpty(userId) && StringUtil.isNotEmpty(postId)) {
                // 分开查岗位和用户，然后进行筛选
                List<User> users = userService.select(new User().setName(userId), 1, 100).getData();
                List<Post> posts = postService.select(new Post().setName(postId), 1, 100).getData();
                users.forEach(u -> {
                    posts.forEach(p -> {
                        employ.setUserId(u.getId())
                                .setPostId(p.getId())
                                .setFirstPeople(firstPeople)
                                .setSecondPeople(secondPeople)
                                .setThirdPeople(thirdPeople)
                                .setId(id);
                        result.addAll(employService.select(employ, 1, 1000).getData());
                    });
                });
            } else if (StringUtil.isEmpty(userId) && StringUtil.isEmpty(postId)) {
                // 第二种情况 岗位和用户都没有传值 直接查询
                employ.setFirstPeople(firstPeople)
                        .setSecondPeople(secondPeople)
                        .setThirdPeople(thirdPeople)
                        .setId(id);
                result.addAll(employService.select(employ, 1, 1000).getData());
            } else {
                // 第三种情况 岗位和用户其中一个传了值 分开查询
                if (StringUtil.isNotEmpty(userId)) {
                    List<User> users = userService.select(new User().setName(userId), 1, 100).getData();
                    users.forEach(u -> {
                        employ.setUserId(u.getId())
                                .setFirstPeople(firstPeople)
                                .setSecondPeople(secondPeople)
                                .setThirdPeople(thirdPeople)
                                .setId(id);
                        result.addAll(employService.select(employ, 1, 1000).getData());
                    });
                }

                if (StringUtil.isNotEmpty(postId)) {
                    List<Post> posts = postService.select(new Post().setName(postId), 1, 100).getData();
                    posts.forEach(p -> {
                        employ.setPostId(p.getId())
                                .setFirstPeople(firstPeople)
                                .setSecondPeople(secondPeople)
                                .setThirdPeople(thirdPeople)
                                .setId(id);
                        result.addAll(employService.select(employ, 1, 1000).getData());
                    });
                }
            }
            // 第四种情况 传值包含状态 那么定向搜索
            if (!Objects.isNull(status)) {
                for (int i = 0; i < status.length; i++) {
                    int finalI = i;
                    res.addAll(result.stream().filter(e -> e.getStatus().equals(status[finalI])).collect(Collectors.toList()));
                }
            } else {
                res.addAll(result);
            }
            // 计算最后一页的大小以免超过限制报错
            int end = Math.min(res.size() - (current - 1) * pageSize, pageSize);
            // 返回值新建一个分页对象直接分割数组
            return new PageResult<>(res.subList((current - 1) * pageSize, (current - 1) * pageSize + end), current, pageSize, true, (long) res.size(), 0);
        } catch (RuntimeException e) {
            return getFailPageResult(404, "查询投递状态失败" + e.getMessage());
        }
    }

    @ApiOperation(value = "查询投递状态（主键）", notes = "查询投递状态（主键）")
    @PostMapping(value = "/selectById")
    @ResponseBody
    public Response<EmployHXYDto> selectById(@RequestParam Long id) {
        try {
            Employ employ = employMapper.selectByPrimaryKey(id);
            EmployHXYDto dto = new EmployHXYDto();

            User user = new User();
            user.setId(employ.getUserId());
            dto.setUserId(userService.select(user, 1, 1).getData().get(0));

            Post post = new Post();
            post.setId(employ.getPostId());
            dto.setPostId(postService.select(post, 1, 1).getData().get(0));

            if (StringUtil.isNotEmpty(employ.getFirstPeople())) {
                user.setId(Long.valueOf(employ.getFirstPeople()));
                dto.setFirstPeople(userService.select(user, 1, 1).getData().get(0));
                dto.setFirstTime(dto.getFirstTime());
            }

            if (StringUtil.isNotEmpty(employ.getSecondPeople())) {
                user.setId(Long.valueOf(employ.getSecondPeople()));
                dto.setSecondPeople(userService.select(user, 1, 1).getData().get(0));
                dto.setSecondTime(employ.getSecondTime());
            }

            if (StringUtil.isNotEmpty(employ.getThirdPeople())) {
                user.setId(Long.valueOf(employ.getThirdPeople()));
                dto.setThirdPeople(userService.select(user, 1, 1).getData().get(0));
                dto.setThirdTime(employ.getThirdTime());
                dto.setThirdEvaluate(employ.getThirdEvaluate());
            }
            if (StringUtil.isNotEmpty(employ.getForthPeople())) {
                user.setId(Long.valueOf(employ.getForthPeople()));
                dto.setForthPeople(userService.select(user, 1, 1).getData().get(0));
                dto.setForthTime(employ.getForthTime());
            }

            if (!Objects.isNull(employ.getTime())) {
                dto.setTime(employ.getTime());
            }
            if (!Objects.isNull(employ.getStatus())) {
                dto.setStatus(employ.getStatus());
            }
            if (!Objects.isNull(employ.getId())) {
                dto.setId(employ.getId());
            }
            if (!Objects.isNull(employ.getUtcCreate())) {
                dto.setUtcCreate(employ.getUtcCreate());
            }
            if (!Objects.isNull(employ.getUtcModify())) {
                dto.setUtcModify(employ.getUtcModify());
            }
            if (StringUtil.isNotEmpty(employ.getCreateBy())) {
                dto.setCreateBy(employ.getCreateBy());
            }
            if (StringUtil.isNotEmpty(employ.getModifyBy())) {
                dto.setModifyBy(employ.getModifyBy());
            }
            if (!Objects.isNull(employ.getValid())) {
                dto.setValid(employ.getValid());
            }
            if (StringUtil.isNotEmpty(employ.getRemark())) {
                dto.setRemark(employ.getRemark());
            }
            return getSuccessResult(dto);
        } catch (RuntimeException e) {
            return getFailResult(404, "查询投递状态失败" + e.getMessage());
        }
    }
}
